import { BlockNoteView } from "@blocknote/shadcn";
import {
  createReactBlockSpec,
  createReactInlineContentSpec,
  SuggestionMenuController,
  useCreateBlockNote,
  getDefaultReactSlashMenuItems,
  type DefaultReactSuggestionItem
} from "@blocknote/react";
import "@blocknote/shadcn/style.css";
import { zh } from "@blocknote/core/locales";
import {
  BlockNoteSchema,
  defaultBlockSpecs,
  defaultInlineContentSpecs,
  defaultStyleSpecs,
  filterSuggestionItems,
  insertOrUpdateBlock
} from "@blocknote/core";
import { CustomSocketProvider } from "./CustomSocketProvider";
import * as Y from "yjs";
import { cursorRender } from "../cursorRender";
import { useParams } from "react-router-dom";
import { useEffect, useMemo, useState } from "react";

// 按文档实例化独立的 Y.Doc（避免不同文档共用同一个 Y.Doc 导致内容错乱/空白）

const schema = BlockNoteSchema.create({
  blockSpecs: {
    ...defaultBlockSpecs,
    blockAI: createReactBlockSpec(
      {
        type: "blockAI",
        content: "none",
        propSchema: {
          id: {
            default: "ai-block"
          },
          title: {
            default: "AI Block"
          },
          description: {
            default: "这是一个AI块的描述."
          },
          content: {
            default: "AI生成的内容"
          }
        }
      },
      {
        render: props => {
          const { id, title, description, content } = props.block.props;
          return (
            <div className="p-4 border rounded-lg shadow-md bg-gray-50 w-lg">
              <h3 className="text-lg font-semibold text-blue-600">{title}</h3>
              <p className="text-xs text-gray-500">{description}</p>
              <div className="mt-2 p-2 bg-white border rounded text-lg text-black">
                <span>内容:</span>
                {content}
              </div>
            </div>
          );
        }
      }
    ),
    blockSignature: createReactBlockSpec(
      {
        type: "blockSignature",
        content: "none",
        propSchema: {
          id: {
            default: "signature-block"
          },
          name: {
            default: "签名"
          }
        }
      },
      {
        render: props => {
          const { name } = props.block.props;
          return (
            <div className="flex item-center justify-between p-2 border rounded shadow-md bg-gray-100">
              <span className="text-sm font-semibold text-gray-600">{name}</span>
            </div>
          );
        }
      }
    )
  },
  inlineContentSpecs: {
    ...defaultInlineContentSpecs,
    mention: createReactInlineContentSpec(
      {
        type: "mention",
        content: "none",
        propSchema: {
          id: {
            default: ""
          },
          name: {
            default: ""
          }
        }
      },
      {
        render: props => {
          const { id } = props.inlineContent.props;
          return <span className="text-blue-500 bg-amber-200">@{id}</span>;
        }
      }
    )
  },
  styleSpecs: {
    ...defaultStyleSpecs
  }
});

// 生成随机颜色
function getRandomColor() {
  return `#${Math.floor(Math.random() * 0xffffff)
    .toString(16)
    .padStart(6, "0")}`;
}

// 生成随机用户名
function getRandomName() {
  return `user-${Math.random().toString(36).slice(2, 8)}`;
}

export function DocEditorDemo() {
  const params = useParams();
  const documentId: string = params.id || "";
  // 每个文档使用独立的 Y.Doc，避免多个文档之间状态串扰或残留
  const ydoc = useMemo(() => new Y.Doc(), [documentId]);
  const provider = useMemo(
    () => new CustomSocketProvider("http://localhost:7002", documentId, ydoc),
    [documentId, ydoc]
  );

  // 由服务端权限驱动的可编辑状态（默认只读）
  const [editable, setEditable] = useState(false);

  const editor = useCreateBlockNote({
    schema,
    dictionary: zh,
    // === 协同编辑配置 ===
    collaboration: {
      // WebSocket 提供者：处理网络通信和实时同步
      provider,

      // 1. 使用 Yjs 协同编辑时 不再使用 initialContent 通过socket服务器 推送 初始内容 这样才不会冲突。
      // Yjs XML 片段：为每个文档创建独立的协同空间
      // 使用文档ID作为片段名称，确保不同文档的协同编辑互不干扰
      // Yjs XML 片段：存储 BlockNote 文档结构的容器
      // 固定片段名为 "blocknote"，与历史数据保持一致（房间按文档ID隔离）
      // fragment: ydoc.getXmlFragment("blocknote"),
      fragment: ydoc.getXmlFragment(`document-${documentId}`),
      // 当前用户信息：用于显示光标和用户状态
      user: {
        name: getRandomName(), // 用户名：显示在光标旁边
        color: getRandomColor() // 用户颜色：光标和选择区域的颜色
      },

      // 光标渲染函数：自定义其他用户光标的显示样式
      renderCursor: cursorRender
    }

    // ⚠️ 注意：使用协同编辑时，不要设置 initialContent
    // 文档内容应该来自协同提供者（Yjs），而不是本地初始化
    // initialContent 会与协同编辑产生冲突

    // 如果需要默认内容，应该在服务器端或首次创建文档时设置
    // initialContent: [...]  // ❌ 协同编辑模式下不要使用
    // initialContent: [
    //   {
    //     type: "blockSignature",
    //     props: {
    //       id: "signature-block-1",
    //       name: "签名"
    //     }
    //   },
    //   {
    //     type: "blockAI",
    //     props: {
    //       id: "ai-block-1",
    //       title: "AI Block 1",
    //       description: "这是第一个AI块的描述.",
    //       content: "AI生成的内容1"
    //     }
    //   },
    //   {
    //     type: "paragraph",
    //     content: [
    //       {
    //         type: "text",
    //         text: "这是一段测试段落，包括一个提及内容",
    //         styles: {}
    //       },
    //       {
    //         type: "mention",
    //         props: { id: "User123", name: "用户123" }
    //       }
    //     ]
    //   }
    // ]
  });

  console.log(typeof (editor as any).setEditable, "333");

  // 监听服务端权限并切换编辑器可编辑状态
  useEffect(() => {
    // socket 服务器 触发 权限变化 事件 这里 是 处理函数
    const applyEditable = (canWrite: boolean) => {
      setEditable(!!canWrite);
    };

    // 初始按 provider 状态应用一次 初始化 权限
    // @ts-ignore
    applyEditable(!!provider.getCanWrite?.() || !!(provider as any).canWrite);

    // 订阅服务端权限事件
    const off = provider.onPermission?.(({ canWrite }) => applyEditable(canWrite));
    return () => {
      if (typeof off === "function") off();
    };
  }, [editor, provider]);

  const getMentionUserItems = (e: typeof editor) => {
    const userItems: DefaultReactSuggestionItem[] = [
      {
        icon: <span>👤</span>,
        title: "用户123",
        onItemClick: () => {
          e.insertInlineContent([
            {
              type: "mention",
              props: { id: "User123", name: "用户123" }
            }
          ]);
        }
      },
      {
        icon: <span>👤</span>,
        title: "渡一用户123",
        onItemClick: () => {
          e.insertInlineContent([
            {
              type: "mention",
              props: { id: "User123", name: "用户123" }
            }
          ]);
        }
      }
    ];
    return userItems;
  };

  const insertBlockAI = (e: typeof editor) => {
    return {
      title: "AI助手",
      subtext: "为您提供智能建议",
      icon: <span>🤖</span>,
      onItemClick: () => {
        insertOrUpdateBlock(e, {
          type: "blockAI",
          props: {
            id: `ai-block-${Date.now()}`,
            title: "AI生成的标题",
            description: "AI生成的描述",
            content: "AI生成的内容"
          }
        });
      }
    };
  };

  const insertBlockSignature = (e: typeof editor) => {
    return {
      title: "签名",
      subtext: "为您提供签名块",
      icon: <span>✍️</span>,
      onItemClick: () => {
        insertOrUpdateBlock(e, {
          type: "blockSignature",
          props: {
            id: `signature-block-${Date.now()}`,
            name: "JACK"
          }
        });
      }
    };
  };

  useEffect(() => {
    if (documentId) {
      // 1. 加载文档基础信息（标题、权限等）
    }
  }, [documentId]);

  const handleInvite = () => {
    console.log("邀请");
    fetch(`/api/documents/${documentId}/invite`, {
      method: "POST",
      credentials: "include",
      body: JSON.stringify({
        userId: 4,
        permission: "write"
        // write read
      }),
      headers: {
        "Content-Type": "application/json"
      }
    })
      .then(res => {
        if (!res.ok) {
          throw new Error(`HTTP ${res.status}: ${res.statusText}`);
        }
        return res.json();
      })
      .then(data => {
        console.log("验证响应:", data);
      });
  };

  return (
    <>
      <div className="relative">
        <div
          className="absolute top-[10px] right-[20px] w-[40px] h-[30px] text-[16px] bg-[#0ea43b] text-[#e2bc23] text-center leading-[30px] border-w-[1px] border-[#e2bc23] rounded-[10px] z-1000"
          onClick={handleInvite}
        >
          邀请
        </div>
        <BlockNoteView editor={editor} slashMenu={false} editable={editable}>
          <SuggestionMenuController
            triggerCharacter="@"
            getItems={async query => {
              return filterSuggestionItems(getMentionUserItems(editor), query);
            }}
          />
          <SuggestionMenuController
            triggerCharacter="/"
            getItems={async query => {
              return filterSuggestionItems(
                [insertBlockSignature(editor), insertBlockAI(editor), ...getDefaultReactSlashMenuItems(editor)],
                query
              );
            }}
          />
        </BlockNoteView>
      </div>
    </>
  );
}
